import barcode from 'barcode.js';
function convert_length(length) {
  return Math.round(wx.getSystemInfoSync().windowWidth * length / 750);
}

function barc(id, code, width, height) {
  barcode.code128(wx.createCanvasContext(id), code, convert_length(width), convert_length(height))
}
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function convert(num) {
  var s = ''
  while (num > 0) {
    var m = num % 26
    if (m === 0) m = 26
    s = (m + 9).toString(36) + s
    num = (num - m) / 26
  }
  return s.toUpperCase()
}

function fomatFloat(num, n) {
  var f = parseFloat(num);
  if (isNaN(f)) {
    return false;
  }
  f = Math.round(num * Math.pow(10, n)) / Math.pow(10, n); // n 幂   
  var s = f.toString();
  var rs = s.indexOf('.');
  //判定如果是整数，增加小数点再补0
  if (rs < 0) {
    rs = s.length;
    s += '.';
  }
  while (s.length <= rs + n) {
    s += '0';
  }
  return s;
} 

/**
  * url后参数处理
  */
function processParas (str) {
  var parasFirstArr = str.split('&');
  var parasObj = {}
  for (var i = 0; i < parasFirstArr.length; i++) {
    var paraName = parasFirstArr[i].split('=')[0];
    var paraVal = parasFirstArr[i].split('=')[1];
    parasObj[paraName] = paraVal
  }
  return parasObj
}

function rangeRandom(num) {
  var min = Math.ceil(num - num * 0.05)
  var max = Math.floor(num + num * 0.05)
  return Math.floor(Math.random() * (max - min) + min);
}

module.exports = {
  formatTime: formatTime,
  barcode: barc,
  convert: convert,
  fomatFloat: fomatFloat,
  processParas: processParas,
  rangeRandom: rangeRandom
}

